package com.fly.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        System.out.println("调用的类名:" + ((HandlerMethod) handler).getBean().getClass().getName());
        System.out.println("调用的方法名:" + ((HandlerMethod) handler).getMethod().getName());
        request.setAttribute("startTime", System.nanoTime());
        return true; //执行后面的方法
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
        long startTime = (long) request.getAttribute("startTime");
        System.out.println("耗时:" + (System.nanoTime() - startTime) / 1000000000.0 + "s");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
        long startTime = (long) request.getAttribute("startTime");
        System.out.println("耗时:" + (System.nanoTime() - startTime) / 1000000000.0 + "s");
        System.out.println("ex:"+ex);
    }
}
